//
//  CoreDataManager.m
//  iCarStyle
//
//  Created by liu nian on 14-4-16.
//  Copyright (c) 2014年 liunian. All rights reserved.
//

#import "CoreDataManager.h"
#import "Article.h"
#import "NewsEntity.h"
#import "PicEntity.h"
#import "PicListEntity.h"
#import "SinglePic.h"
#import "PicModel.h"
#import "NewsTextEntity.h"
#import "NewsImgEntity.h"

@interface CoreDataManager ()
@property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;
@end

@implementation CoreDataManager

+ (CoreDataManager *)sharedManager{
    static CoreDataManager * sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManager = [[CoreDataManager alloc] init];
    });
    return sharedManager;
}
- (id)init
{
    self = [super init];
    if (self) {
        self.managedObjectContext = [NSManagedObjectContext MR_contextWithParent:[NSManagedObjectContext MR_defaultContext]];
    }
    return self;
}

- (NewsEntity *)makeNewsEntity:(NewsEntity *)entity WithAritcle:(Article *)article{
    if (article) {
        [entity setNid:[NSNumber numberWithInteger:article.nid]];
        [entity setCid:[NSNumber numberWithInteger:article.cid]];
        [entity setTitle:article.title];
        [entity setIcon:article.icon];
        [entity setDate:article.date];
        [entity setLink:article.link];
        [entity setDesc:article.desc];
        [entity setContent:article.content];
        [entity setFavorit:[NSNumber numberWithBool:article.isFavorit]];
        return entity;
    }
    return nil;
}

#pragma mark makePic
- (PicEntity *)makePicEntity:(PicEntity *)entity WithSinglePic:(SinglePic *)singlePic{
    if (singlePic) {
        [entity setCid:[NSNumber numberWithInteger:singlePic.cid]];
        [entity setIndex:[NSNumber numberWithInteger:singlePic.index]];
        [entity setBigimg:singlePic.big];
        [entity setSmallimg:singlePic.small];
        [entity setUrl:singlePic.link];
        [entity setIntro:singlePic.intro];
        return entity;
    }
    return nil;
}

- (PicListEntity *)makePicListEntity:(PicListEntity *)entity WithPicture:(PicModel *)picture{
    if (picture) {
        [entity setId:[NSNumber numberWithInteger:picture.cid]];
        [entity setTitle:picture.title];
        [entity setUrl:picture.link];
        [entity setThumbnail:picture.thumal];
        [entity setTotal:[NSNumber numberWithInteger:picture.total]];
        return entity;
    }
    return nil;
}

- (void)insertArticle:(Article *)article{
    if (article == nil) {
        return;
    }
    NewsEntity *entity = [NewsEntity MR_findFirstWithPredicate:[NSPredicate predicateWithFormat:@"(nid == %d)",article.nid]];
    if (entity) {

    }else{
        entity= [NewsEntity MR_createInContext:self.managedObjectContext];
        [entity setCreate:[NSDate date]];
    }
    entity = [self makeNewsEntity:entity WithAritcle:article];
    [[entity managedObjectContext] MR_saveToPersistentStoreAndWait];

}

- (NSArray *)singlePicsForPicture:(PicModel *)picture{
    NSArray *picEntities = [PicEntity MR_findAllSortedBy:@"index"
                                               ascending:YES
                                           withPredicate:[NSPredicate predicateWithFormat:@"(cid == %d) AND (url == %d)",picture.cid,picture.link]
                                               inContext:self.managedObjectContext];
    NSMutableArray *array = nil;
    if (picEntities.count) {
        array = [NSMutableArray arrayWithCapacity:picEntities.count];
        for (PicEntity *entity in picEntities) {
            SinglePic *pic = [[SinglePic alloc] initWithPicEntity:entity];
            [array addObject:pic];
        }
    }

    return array;

}

- (void)insertSinglePic:(SinglePic *)singlePic{
    if (singlePic == nil) {
        return;
    }
    PicEntity *entity = [PicEntity MR_findFirstWithPredicate:[NSPredicate predicateWithFormat:@"(cid == %d) AND (index == %d)",singlePic.cid,singlePic.index]];
    if (!entity) {
        entity= [PicEntity MR_createInContext:self.managedObjectContext];
    }
    entity = [self makePicEntity:entity WithSinglePic:singlePic];
    [[entity managedObjectContext] MR_saveOnlySelfAndWait];
//    [[entity managedObjectContext] MR_saveToPersistentStoreAndWait];
}

- (void)insertPicture:(PicModel *)picture{
    if (picture == nil) {
        return;
    }
    PicListEntity *entity = [PicListEntity MR_findFirstWithPredicate:[NSPredicate predicateWithFormat:@"(cid == %d)",picture.cid]];
    if (!entity) {
        entity= [PicListEntity MR_createInContext:self.managedObjectContext];
    }
    entity = [self makePicListEntity:entity WithPicture:picture];

    for (SinglePic *pic in picture.SinglePics) {
        [self insertSinglePic:pic];
    }

    [[entity managedObjectContext] MR_saveToPersistentStoreAndWait];
}
- (void)getArticles{}

- (void)insertNewsText:(NewsText *)newsText{
    NewsTextEntity *entity = [NewsTextEntity MR_findFirstWithPredicate:[NSPredicate predicateWithFormat:@"(nid = %d) AND (index = %d)",newsText.nid,newsText.index]
                                                             inContext:self.managedObjectContext];
    if (!entity) {
        entity = [NewsTextEntity MR_createInContext:self.managedObjectContext];
    }

    [entity setNid:[NSNumber numberWithInt:newsText.nid]];
    [entity setContent:newsText.content];
    [entity setIndex:[NSNumber numberWithInteger:newsText.index]];
    [[entity managedObjectContext] MR_saveToPersistentStoreAndWait];
}

- (void)insertNewsImg:(NewsImg *)newsImg{
    NewsImgEntity *entity = [NewsImgEntity MR_findFirstWithPredicate:[NSPredicate predicateWithFormat:@"(nid = %d) AND (index = %d)",newsImg.nid,newsImg.index]
                                                             inContext:self.managedObjectContext];
    if (!entity) {
        entity = [NewsImgEntity MR_createInContext:self.managedObjectContext];
    }

    [entity setNid:[NSNumber numberWithInt:newsImg.nid]];
    [entity setSrc:newsImg.src];
    [entity setAlt:newsImg.alt];
    [entity setIndex:[NSNumber numberWithInteger:newsImg.index]];
    [[entity managedObjectContext] MR_saveToPersistentStoreAndWait];
}

- (BOOL)isFavArticle:(Article *)article{
    NewsEntity *entity = [NewsEntity MR_findFirstWithPredicate:[NSPredicate predicateWithFormat:@"(nid == %d)",article.nid]
                                                     inContext:self.managedObjectContext];
    return [entity.favorit boolValue];
}

- (NewsArticle *)newsArticleWithArticle:(Article *)article{
    [NewsTextEntity MR_findAll];
    NSArray *texts = [NewsTextEntity MR_findAllSortedBy:@"index" ascending:YES withPredicate:[NSPredicate predicateWithFormat:@"(nid = %d)",article.nid] inContext:self.managedObjectContext];

    NSArray *images = [NewsImgEntity MR_findAllSortedBy:@"index" ascending:YES withPredicate:[NSPredicate predicateWithFormat:@"nid = %d",article.nid] inContext:self.managedObjectContext];

    NSMutableArray *news_texts = nil;
    if (texts && texts.count) {
        news_texts = [NSMutableArray arrayWithCapacity:texts.count];
        for (NewsTextEntity *entity in texts) {
            NewsText *textNews = [[NewsText alloc] instancetypeWithNewsTextEntity:entity];
            [news_texts addObject:textNews];
        }
    }

    NSMutableArray *news_images = nil;
    if (images && images.count) {
        news_images = [NSMutableArray arrayWithCapacity:images.count];
        for (NewsImgEntity *entity in images) {
            NewsImg *imgNews = [[NewsImg alloc] instancetypeWithNewsImgEntity:entity];
            [news_images addObject:imgNews];
        }
    }

    NewsArticle *newsArticle = [[NewsArticle alloc] instancetypeWithArticle:article];
    newsArticle.newsImages = news_images;
    newsArticle.newsTexts = news_texts;
    return newsArticle;
}

- (void)favArticle:(Article *)article{
    [article setFavorit:YES];
    [self insertArticle:article];
}
- (void)cancelFavArticle:(Article *)article{
    [article setFavorit:NO];
    [self insertArticle:article];
}
@end
